package com.enfi.api.modules.db.service.impl;

import com.enfi.api.modules.db.base.BaseQuery;
import com.enfi.api.modules.db.base.BaseServiceImpl;
import com.enfi.api.modules.db.dao.WarningRepository;
import com.enfi.api.modules.db.entity.Warning;
import com.enfi.api.modules.db.service.WarningService;
import com.enfi.api.util.SecUser;
import com.enfi.api.util.SpeUtils;
import com.enfi.api.util.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Objects;

/**
 * (Warning)表服务实现类
 *
 * @author wind
 * @since 2020-04-07 15:59:42
 */
@Service("warningService")
@NoRepositoryBean
public class WarningServiceImpl extends BaseServiceImpl<WarningRepository,Warning,Integer> implements WarningService {

    @Override
    protected Object query(BaseQuery baseQuery, Warning warning, Pageable pageable) {
        Assert.isTrue(baseQuery.getQuery()!=null&&baseQuery.getQuery().getQueryType()!=null,"查询方式不为空");
        switch (baseQuery.getQuery().getQueryType()){
            case "":
                return this.baseRepository.findAll((root,query,builder)->{
                    List<Predicate> predicates= SpeUtils.getInstance().toSpec(warning,baseQuery,root,builder);
                    query.where(predicates.stream().toArray(Predicate[]::new));
                    SecUser secUser=UserUtils.getSecUserOrNo();
                    if(secUser!=null&&!StringUtils.equalsIgnoreCase(secUser.getUsername(),"system")){
                        Join join = root.join("warningRoles", JoinType.LEFT);
                        predicates.add(builder.and(join.get("roleId").in(secUser.getAuthoritiesToList())));
                    }
                    if(secUser!=null){
                        Join join1 = root.join("warningViews", JoinType.LEFT);
                        if (!Objects.isNull(warning.getViewStatus())) {
                            predicates.add(builder.and(builder.equal(join1.get("userId"), secUser.getUsername())));
                            predicates.add(builder.and(builder.equal(join1.get("viewStatus"),warning.getViewStatus())));
                        }
                    }
                    query.where(predicates.stream().toArray(Predicate[]::new));
                    return null;
                },pageable);
            default:
                return super.query(baseQuery,warning,pageable);
        }
    }
}